#include "ring_queue.hpp"
#include "Task.hpp"
#include <iostream>
#include <ctime>
#include <cstring>
#include <unistd.h>

using namespace std;

// 先单，再多线程
template <typename T>
struct thread_info
{
    rbqueue<T> *pq;
    string name;
};

void *consume(void *args)
{
    thread_info<task> *pt = static_cast<thread_info<task> *>(args);
    auto pq = pt->pq;
    while (true)
    {
        task t;
        pq->pop(&t);
        t.run();
        printf("%s 处理了一个任务： %s\n", pt->name.c_str(), t.get_result().c_str());
        sleep(1);
    }
    return nullptr;
}

void *produce(void *args)
{
    size_t len = strlen(operaters);
    thread_info<task> *pt = static_cast<thread_info<task> *>(args);
    auto pq = pt->pq;
    while (true)
    {
        int data1 = rand() % 10 + 1;
        int data2 = rand() % 10;
        // cout << data1 << ' ' << data2 << endl;
        char op = operaters[rand() % 4];
        // cout << op << endl;
        task t(data1, data2, op);
        // cout << ".\n";
        pq->push(t);
        // cout << "..\n";
        printf("%s 产生了一个任务： %s\n", pt->name.c_str(), t.get_task().c_str());
        // cout << "...\n";
    }
    return nullptr;
}
int main()
{
    srand(time(nullptr) ^ getpid());
    rbqueue<task> *rq = new rbqueue<task>(5);
    pthread_t c[3], p[3];
    for (int i = 0; i < 3; ++i)
    {
        thread_info<task> *tf_c = new thread_info<task>{rq, "consumer-" + to_string(i)};
        thread_info<task> *tf_p = new thread_info<task>{rq, "produce-" + to_string(i)};
        pthread_create(c + i, nullptr, consume, tf_c);
        pthread_create(p + i, nullptr, produce, tf_p);
    }
    for(int i = 0; i < 3; ++i)
    {
        pthread_join(c[i], nullptr);
        pthread_join(p[i], nullptr);
    }

    return 0;
}